package me.sauce.folkpocket48

import android.annotation.SuppressLint
import android.app.Application
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.support.annotation.VisibleForTesting
import me.sauce.folkpocket48.home.refresh.RefreshViewModule

/**
 * @author sauceWu
 * @since 2018/1/4 15:36
 */
class ViewModelFactory private constructor(private val application: Application) : ViewModelProvider.NewInstanceFactory() {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        when (modelClass){
            RefreshViewModule::class.java -> {
                return RefreshViewModule(application) as T
            }
        }
        return super.create(modelClass)
    }
    companion object {

        @SuppressLint("StaticFieldLeak")
        @Volatile private var INSTANCE: ViewModelFactory? = null

        fun getInstance(application: Application) =
                INSTANCE ?: synchronized(ViewModelFactory::class.java) {
                    INSTANCE ?: ViewModelFactory(application)
                            .also { INSTANCE = it }
                }


        @VisibleForTesting
        fun destroyInstance() {
            INSTANCE = null
        }
    }
}